import json

from flask import Blueprint, request, jsonify
from application.models.users.user import *
user_blue = Blueprint("userblue",__name__)

#相册展示
@user_blue.route('/get_lei')
def get_lei():
    data = ZhangTpye.query.all()
    list = [{"id": i.id, "name": i.name} for i in data]
    return jsonify({"code": 200, "list": list})
# 相册的添加
@user_blue.route('/add_xc', methods=['POST'])
def add_xc():
    data = json.loads(request.data)
    xc = ZhangTpye(name=data["name"])
    db.session.add(xc)
    db.session.commit()
    return jsonify({"code": 200, "mes": "添加成功"})
# 相册删除
@user_blue.route("/del_xc", methods=['DELETE'])
def del_xc():
    # 接收
    id = request.args.get("id")
    # 删除
    ZhangTpye.query.filter(ZhangTpye.id == id).delete()
    db.session.commit()
    # 返回
    return jsonify({"code": 200, "mes": "删除成功"})


import os

# 本地保存图片
@user_blue.route("/upload", methods=['POST'])
def upload():
    # 接收参数
    file = request.files.get("file")
    filename = file.filename
    path = os.path.join("static/upload"+filename)
    file.save(path)
    return jsonify({"code": 200, "url": path})


# 修改相册
@user_blue.route("/up_xiang", methods=["PUT"])
def up_xiang():
    # 接收参数
    data = json.loads(request.data)
    # 修改
    ZhangTpye.query.filter(ZhangTpye.id == data['id']).update({
        "id": data['id'],
        "name": data["name"]
    })
    db.session.commit()
    return jsonify({"code": 200, "mes": "修改成功"})


# 添加图片
@user_blue.route('/get_add', methods=["POST"])
def get_add():
    # 接收参数
    data = json.loads(request.data)
    # 进行添加
    zp = Zhangs(name=data["name"], url=data["url"], zid=data["zid"])
    db.session.add(zp)
    db.session.commit()
    # 返回
    return jsonify({"code": 200, "mes": "添加成功"})




# 修改图片
@user_blue.route("/get_put", methods=["PUT"])
def get_put():
    # 接收参数
    data = json.loads(request.data)

    # 修改参数
    Zhangs.query.filter(Zhangs.id == data['id']).update({
        "id": data['id'],
        "name": data['name'],
        "url": data['url'],
        "zid": data['zid']
    })
    db.session.commit()
    return jsonify({"code": 200, "mes": "修改成功"})

# 删除图片
@user_blue.route("/get_del", methods=["DELETE"])
def get_del():
    # 接收参数
    id = request.args.get('id')

    # 删除数据
    Zhangs.query.filter(Zhangs.id == id).delete()
    db.session.commit()
    # 返回响应
    return jsonify({"code": 200, "mes": "删除成功"})

# 相册展示全部
@user_blue.route("/get_all")
def get_all():
    id = request.args.get('id')
    data = Zhangs.query.filter(Zhangs.zid == id)
    list = [{"id": i.id, "url": i.url} for i in data]
    return jsonify({"code": 200, "mes": list})